package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.mapper.OmsStatisticsMapper;
import org.jeecg.modules.oms.service.IOmsStatisticsService;
import org.jeecg.modules.oms.service.IProductSalesOrderService;
import org.jeecg.modules.oms.vo.CustomerStatisticsVO;
import org.jeecg.modules.oms.vo.SalesOverviewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: OMS销售统计服务实现
 * @Author: jeecg-boot
 * @Date: 2025-01-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class OmsStatisticsServiceImpl implements IOmsStatisticsService {

    @Autowired
    private OmsStatisticsMapper omsStatisticsMapper;

    @Autowired
    private IProductSalesOrderService productSalesOrderService;

    @Override
    public SalesOverviewVO getSalesOverview(String startDate, String endDate) {
        try {
            SalesOverviewVO overview = new SalesOverviewVO();
            
            // 获取当前日期
            LocalDate today = LocalDate.now();
            LocalDate weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1);
            LocalDate monthStart = today.withDayOfMonth(1);
            LocalDate yearStart = today.withDayOfYear(1);
            
            // 获取去年同期数据用于计算增长率
            LocalDate lastYearMonthStart = monthStart.minusYears(1);
            LocalDate lastYearMonthEnd = today.minusYears(1);
            LocalDate lastYearYearStart = yearStart.minusYears(1);
            LocalDate lastYearYearEnd = today.minusYears(1);

            // 今日销售数据
            Map<String, Object> todayData = omsStatisticsMapper.getSalesStatistics(
                today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            overview.setTodaySales(getBigDecimalValue(todayData, "totalAmount"));
            overview.setTodayOrderCount(getIntegerValue(todayData, "orderCount"));

            // 本周销售数据
            Map<String, Object> weekData = omsStatisticsMapper.getSalesStatistics(
                weekStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            overview.setWeekSales(getBigDecimalValue(weekData, "totalAmount"));
            overview.setWeekOrderCount(getIntegerValue(weekData, "orderCount"));

            // 本月销售数据
            Map<String, Object> monthData = omsStatisticsMapper.getSalesStatistics(
                monthStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            overview.setMonthSales(getBigDecimalValue(monthData, "totalAmount"));
            overview.setMonthOrderCount(getIntegerValue(monthData, "orderCount"));

            // 本年销售数据
            Map<String, Object> yearData = omsStatisticsMapper.getSalesStatistics(
                yearStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            overview.setYearSales(getBigDecimalValue(yearData, "totalAmount"));
            overview.setYearOrderCount(getIntegerValue(yearData, "orderCount"));

            // 计算平均订单金额
            BigDecimal totalAmount = overview.getYearSales();
            Integer totalCount = overview.getYearOrderCount();
            if (totalCount != null && totalCount > 0 && totalAmount != null) {
                overview.setAvgOrderAmount(totalAmount.divide(new BigDecimal(totalCount), 2, RoundingMode.HALF_UP));
            } else {
                overview.setAvgOrderAmount(BigDecimal.ZERO);
            }

            // 计算月同比增长率
            Map<String, Object> lastYearMonthData = omsStatisticsMapper.getSalesStatistics(
                lastYearMonthStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                lastYearMonthEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            BigDecimal lastYearMonthSales = getBigDecimalValue(lastYearMonthData, "totalAmount");
            if (lastYearMonthSales != null && lastYearMonthSales.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal monthGrowth = overview.getMonthSales().subtract(lastYearMonthSales)
                    .divide(lastYearMonthSales, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100));
                overview.setMonthGrowthRate(monthGrowth);
            } else {
                overview.setMonthGrowthRate(BigDecimal.ZERO);
            }

            // 计算年同比增长率并设置去年同期数据
            Map<String, Object> lastYearYearData = omsStatisticsMapper.getSalesStatistics(
                lastYearYearStart.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                lastYearYearEnd.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            BigDecimal lastYearYearSales = getBigDecimalValue(lastYearYearData, "totalAmount");
            Integer lastYearYearOrderCount = getIntegerValue(lastYearYearData, "orderCount");
            
            // 设置去年同期数据
            overview.setLastYearMonthSales(lastYearMonthSales);
            overview.setLastYearYearSales(lastYearYearSales);
            overview.setLastYearMonthOrderCount(getIntegerValue(lastYearMonthData, "orderCount"));
            overview.setLastYearYearOrderCount(lastYearYearOrderCount);
            
            if (lastYearYearSales != null && lastYearYearSales.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal yearGrowth = overview.getYearSales().subtract(lastYearYearSales)
                    .divide(lastYearYearSales, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100));
                overview.setYearGrowthRate(yearGrowth);
            } else {
                overview.setYearGrowthRate(BigDecimal.ZERO);
            }

            // 获取销售趋势数据 (最近12个月)
            overview.setTrendData(getSalesTrend("month", 12));

            // 获取订单状态分布
            overview.setStatusDistribution(getOrderStatusDistribution(startDate, endDate));

            return overview;
        } catch (Exception e) {
            log.error("获取销售概览统计数据失败", e);
            throw new RuntimeException("获取销售概览统计数据失败", e);
        }
    }

    @Override
    public List<SalesOverviewVO.SalesTrendItem> getSalesTrend(String period, Integer limit) {
        try {
            List<Map<String, Object>> trendData = omsStatisticsMapper.getSalesTrend(period, limit);
            List<SalesOverviewVO.SalesTrendItem> result = new ArrayList<>();
            
            for (Map<String, Object> item : trendData) {
                SalesOverviewVO.SalesTrendItem trendItem = new SalesOverviewVO.SalesTrendItem();
                trendItem.setDate(getString(item, "date"));
                trendItem.setAmount(getBigDecimalValue(item, "amount"));
                trendItem.setOrderCount(getIntegerValue(item, "orderCount"));
                result.add(trendItem);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取销售趋势数据失败", e);
            throw new RuntimeException("获取销售趋势数据失败", e);
        }
    }

    @Override
    public List<SalesOverviewVO.OrderStatusItem> getOrderStatusDistribution(String startDate, String endDate) {
        try {
            List<Map<String, Object>> statusData = omsStatisticsMapper.getOrderStatusDistribution(startDate, endDate);
            List<SalesOverviewVO.OrderStatusItem> result = new ArrayList<>();
            
            // 计算总订单数用于计算占比
            int totalCount = statusData.stream().mapToInt(item -> getIntegerValue(item, "count")).sum();
            
            for (Map<String, Object> item : statusData) {
                SalesOverviewVO.OrderStatusItem statusItem = new SalesOverviewVO.OrderStatusItem();
                statusItem.setStatusName(item.get("statusName").toString());
                statusItem.setStatusValue(item.get("orderStatus").toString());
                statusItem.setCount(getIntegerValue(item, "count"));
                
                // 计算占比
                if (totalCount > 0) {
                    BigDecimal percentage = new BigDecimal(statusItem.getCount())
                        .divide(new BigDecimal(totalCount), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100));
                    statusItem.setPercentage(percentage);
                } else {
                    statusItem.setPercentage(BigDecimal.ZERO);
                }
                
                result.add(statusItem);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取订单状态分布失败", e);
            throw new RuntimeException("获取订单状态分布失败", e);
        }
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(String statusValue) {
        if (StringUtils.isEmpty(statusValue)) {
            return "未知";
        }
        switch (statusValue) {
            case "0": return "待确认";
            case "1": return "已确认";
            case "2": return "生产中";
            case "3": return "已完成";
            case "4": return "已取消";
            default: return "未知";
        }
    }

    /**
     * 安全获取BigDecimal值
     */
    private BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 安全获取Integer值
     */
    private Integer getIntegerValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return 0;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * 安全获取String值
     */
    private String getString(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? value.toString() : "";
    }

    @Override
    public CustomerStatisticsVO.CustomerOverviewVO getCustomerOverview(String startDate, String endDate) {
        try {
            CustomerStatisticsVO.CustomerOverviewVO overview = new CustomerStatisticsVO.CustomerOverviewVO();
            
            // 从数据库获取当前期间的客户统计数据
            Map<String, Object> currentData = omsStatisticsMapper.getCustomerOverviewStatistics(startDate, endDate);
            
            // 设置当前期间数据和增长率（SQL中已经计算好）
            overview.setTotalCustomers(getIntegerValue(currentData, "totalCustomers"));
            overview.setActiveCustomers(getIntegerValue(currentData, "activeCustomers"));
            overview.setNewCustomers(getIntegerValue(currentData, "newCustomers"));
            overview.setAvgOrderAmount(getBigDecimalValue(currentData, "avgOrderAmount"));
            
            // 设置增长率（从SQL查询结果中直接获取）
            overview.setCustomerGrowthRate(getBigDecimalValue(currentData, "customerGrowthRate"));
            overview.setActiveGrowthRate(getBigDecimalValue(currentData, "activeGrowthRate"));
            overview.setNewGrowthRate(getBigDecimalValue(currentData, "newGrowthRate"));
            overview.setAvgAmountGrowthRate(getBigDecimalValue(currentData, "avgAmountGrowthRate"));
            
            return overview;
        } catch (Exception e) {
            log.error("获取客户概览统计数据失败", e);
            throw new RuntimeException("获取客户概览统计数据失败", e);
        }
    }

    @Override
    public List<CustomerStatisticsVO.CustomerRankingItem> getCustomerSalesRanking(String startDate, String endDate, Integer limit) {
        try {
            List<CustomerStatisticsVO.CustomerRankingItem> result = new ArrayList<>();
            
            // 从数据库获取客户销售金额排行数据
            List<Map<String, Object>> rankingData = omsStatisticsMapper.getCustomerSalesRanking(startDate, endDate, limit);
            
            for (int i = 0; i < rankingData.size(); i++) {
                Map<String, Object> item = rankingData.get(i);
                CustomerStatisticsVO.CustomerRankingItem rankingItem = new CustomerStatisticsVO.CustomerRankingItem();
                
                rankingItem.setRank(i + 1);
                rankingItem.setCustomerId(getString(item, "customerId"));
                rankingItem.setCustomerName(getString(item, "customerName"));
                rankingItem.setSalesAmount(getBigDecimalValue(item, "salesAmount"));
                rankingItem.setOrderCount(getIntegerValue(item, "orderCount"));
                rankingItem.setPercentage(getBigDecimalValue(item, "percentage"));
                
                // 计算增长率（需要去年同期数据）
                if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                    try {
                        LocalDate start = LocalDate.parse(startDate);
                        LocalDate end = LocalDate.parse(endDate);
                        String lastYearStartDate = start.minusYears(1).toString();
                        String lastYearEndDate = end.minusYears(1).toString();
                        
                        // 获取该客户去年同期的销售金额
                        List<Map<String, Object>> lastYearData = omsStatisticsMapper.getCustomerSalesRanking(lastYearStartDate, lastYearEndDate, null);
                        BigDecimal lastYearAmount = BigDecimal.ZERO;
                        
                        for (Map<String, Object> lastYearItem : lastYearData) {
                            if (getString(lastYearItem, "customerId").equals(rankingItem.getCustomerId())) {
                                lastYearAmount = getBigDecimalValue(lastYearItem, "salesAmount");
                                break;
                            }
                        }
                        
                        // 计算增长率
                        if (lastYearAmount.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal growthRate = rankingItem.getSalesAmount().subtract(lastYearAmount)
                                .divide(lastYearAmount, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal(100));
                            rankingItem.setGrowthRate(growthRate);
                        } else {
                            rankingItem.setGrowthRate(BigDecimal.ZERO);
                        }
                    } catch (Exception e) {
                        log.warn("计算客户销售增长率失败，使用默认值", e);
                        rankingItem.setGrowthRate(BigDecimal.ZERO);
                    }
                } else {
                    rankingItem.setGrowthRate(BigDecimal.ZERO);
                }
                
                result.add(rankingItem);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取客户销售金额排行榜失败", e);
            throw new RuntimeException("获取客户销售金额排行榜失败", e);
        }
    }

    @Override
    public List<CustomerStatisticsVO.CustomerRankingItem> getCustomerOrderRanking(String startDate, String endDate, Integer limit) {
        try {
            List<CustomerStatisticsVO.CustomerRankingItem> result = new ArrayList<>();
            
            // 从数据库获取客户订单数量排行数据
            List<Map<String, Object>> rankingData = omsStatisticsMapper.getCustomerOrderRanking(startDate, endDate, limit);
            
            for (int i = 0; i < rankingData.size(); i++) {
                Map<String, Object> item = rankingData.get(i);
                CustomerStatisticsVO.CustomerRankingItem rankingItem = new CustomerStatisticsVO.CustomerRankingItem();
                
                rankingItem.setRank(i + 1);
                rankingItem.setCustomerId(getString(item, "customerId"));
                rankingItem.setCustomerName(getString(item, "customerName"));
                rankingItem.setOrderCount(getIntegerValue(item, "orderCount"));
                rankingItem.setSalesAmount(getBigDecimalValue(item, "salesAmount"));
                rankingItem.setPercentage(getBigDecimalValue(item, "percentage"));
                
                // 计算增长率（需要去年同期数据）
                if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
                    try {
                        LocalDate start = LocalDate.parse(startDate);
                        LocalDate end = LocalDate.parse(endDate);
                        String lastYearStartDate = start.minusYears(1).toString();
                        String lastYearEndDate = end.minusYears(1).toString();
                        
                        // 获取该客户去年同期的订单数量
                        List<Map<String, Object>> lastYearData = omsStatisticsMapper.getCustomerOrderRanking(lastYearStartDate, lastYearEndDate, null);
                        Integer lastYearOrderCount = 0;
                        
                        for (Map<String, Object> lastYearItem : lastYearData) {
                            if (getString(lastYearItem, "customerId").equals(rankingItem.getCustomerId())) {
                                lastYearOrderCount = getIntegerValue(lastYearItem, "orderCount");
                                break;
                            }
                        }
                        
                        // 计算增长率
                        if (lastYearOrderCount > 0) {
                            BigDecimal growthRate = new BigDecimal(rankingItem.getOrderCount() - lastYearOrderCount)
                                .divide(new BigDecimal(lastYearOrderCount), 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal(100));
                            rankingItem.setGrowthRate(growthRate);
                        } else {
                            rankingItem.setGrowthRate(BigDecimal.ZERO);
                        }
                    } catch (Exception e) {
                        log.warn("计算客户订单增长率失败，使用默认值", e);
                        rankingItem.setGrowthRate(BigDecimal.ZERO);
                    }
                } else {
                    rankingItem.setGrowthRate(BigDecimal.ZERO);
                }
                
                result.add(rankingItem);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取客户订单数量排行榜失败", e);
            throw new RuntimeException("获取客户订单数量排行榜失败", e);
        }
    }

    @Override
    public CustomerStatisticsVO.CustomerContributionVO getCustomerContribution(String startDate, String endDate, String type) {
        try {
            CustomerStatisticsVO.CustomerContributionVO contribution = new CustomerStatisticsVO.CustomerContributionVO();
            
            // 从数据库获取客户贡献度分析数据
            Map<String, Object> contributionData = omsStatisticsMapper.getCustomerContribution(startDate, endDate, type);
            
            if ("sales".equals(type)) {
                contribution.setTop10Amount(getBigDecimalValue(contributionData, "top10Amount"));
                contribution.setOthersAmount(getBigDecimalValue(contributionData, "othersAmount"));
                contribution.setTop10Percentage(getBigDecimalValue(contributionData, "top10Percentage"));
                contribution.setOthersPercentage(getBigDecimalValue(contributionData, "othersPercentage"));
            } else {
                contribution.setTop10Orders(getIntegerValue(contributionData, "top10Orders"));
                contribution.setOthersOrders(getIntegerValue(contributionData, "othersOrders"));
                contribution.setTop10Percentage(getBigDecimalValue(contributionData, "top10Percentage"));
                contribution.setOthersPercentage(getBigDecimalValue(contributionData, "othersPercentage"));
            }
            
            return contribution;
        } catch (Exception e) {
            log.error("获取客户贡献度分析数据失败", e);
            throw new RuntimeException("获取客户贡献度分析数据失败", e);
        }
    }

    @Override
    public CustomerStatisticsVO.CustomerAnalysisVO getCustomerAnalysis(String startDate, String endDate, String type) {
        try {
            CustomerStatisticsVO.CustomerAnalysisVO analysis = new CustomerStatisticsVO.CustomerAnalysisVO();
            
            // 从数据库获取新老客户分析数据
            Map<String, Object> analysisData = omsStatisticsMapper.getCustomerAnalysis(startDate, endDate, type);
            
            if ("count".equals(type)) {
                analysis.setNewCustomerCount(getIntegerValue(analysisData, "newCustomerCount"));
                analysis.setOldCustomerCount(getIntegerValue(analysisData, "oldCustomerCount"));
                analysis.setNewCustomerPercentage(getBigDecimalValue(analysisData, "newCustomerPercentage"));
                analysis.setOldCustomerPercentage(getBigDecimalValue(analysisData, "oldCustomerPercentage"));
            } else {
                analysis.setNewCustomerAmount(getBigDecimalValue(analysisData, "newCustomerAmount"));
                analysis.setOldCustomerAmount(getBigDecimalValue(analysisData, "oldCustomerAmount"));
                analysis.setNewCustomerPercentage(getBigDecimalValue(analysisData, "newCustomerPercentage"));
                analysis.setOldCustomerPercentage(getBigDecimalValue(analysisData, "oldCustomerPercentage"));
            }
            
            return analysis;
        } catch (Exception e) {
            log.error("获取新老客户分析数据失败", e);
            throw new RuntimeException("获取新老客户分析数据失败", e);
        }
    }

    // ==================== 产品销售分析相关方法实现 ====================

    @Override
    public Object getProductOverview(String startDate, String endDate) {
        try {
            // 获取产品销售概览统计数据
            Map<String, Object> overviewData = omsStatisticsMapper.getProductOverviewStatistics(startDate, endDate);
            
            // 获取去年同期数据用于计算增长率
            String lastYearStartDate = null;
            String lastYearEndDate = null;
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                lastYearStartDate = start.minusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                lastYearEndDate = end.minusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
            
            Map<String, Object> lastYearData = omsStatisticsMapper.getProductOverviewStatistics(lastYearStartDate, lastYearEndDate);
            
            // 构建返回数据
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("totalSales", getBigDecimalValue(overviewData, "totalSales"));
            result.put("totalOrders", getIntegerValue(overviewData, "totalOrders"));
            result.put("totalProducts", getIntegerValue(overviewData, "totalProducts"));
            result.put("avgOrderAmount", getBigDecimalValue(overviewData, "avgOrderAmount"));
            
            // 计算增长率
            BigDecimal currentSales = getBigDecimalValue(overviewData, "totalSales");
            BigDecimal lastYearSales = getBigDecimalValue(lastYearData, "totalSales");
            result.put("salesGrowthRate", calculateGrowthRate(currentSales, lastYearSales));
            
            Integer currentOrders = getIntegerValue(overviewData, "totalOrders");
            Integer lastYearOrders = getIntegerValue(lastYearData, "totalOrders");
            result.put("ordersGrowthRate", calculateGrowthRate(new BigDecimal(currentOrders), new BigDecimal(lastYearOrders)));
            
            Integer currentProducts = getIntegerValue(overviewData, "totalProducts");
            Integer lastYearProducts = getIntegerValue(lastYearData, "totalProducts");
            result.put("productsGrowthRate", calculateGrowthRate(new BigDecimal(currentProducts), new BigDecimal(lastYearProducts)));
            
            BigDecimal currentAvgAmount = getBigDecimalValue(overviewData, "avgOrderAmount");
            BigDecimal lastYearAvgAmount = getBigDecimalValue(lastYearData, "avgOrderAmount");
            result.put("avgAmountGrowthRate", calculateGrowthRate(currentAvgAmount, lastYearAvgAmount));
            
            // 去年同期数据
            result.put("lastYearSales", lastYearSales);
            result.put("lastYearOrders", lastYearOrders);
            result.put("lastYearProducts", lastYearProducts);
            result.put("lastYearAvgAmount", lastYearAvgAmount);
            
            return result;
        } catch (Exception e) {
            log.error("获取产品销售概览统计数据失败", e);
            throw new RuntimeException("获取产品销售概览统计数据失败", e);
        }
    }

    @Override
    public Object getProductSeriesRanking(String startDate, String endDate, Integer limit) {
        try {
            List<Map<String, Object>> rankingData = omsStatisticsMapper.getProductSeriesRanking(startDate, endDate, limit);
            return rankingData;
        } catch (Exception e) {
            log.error("获取产品系列销售排行榜失败", e);
            throw new RuntimeException("获取产品系列销售排行榜失败", e);
        }
    }

    @Override
    public Object getProductColorAnalysis(String startDate, String endDate, String seriesName) {
        try {
            List<Map<String, Object>> colorData = omsStatisticsMapper.getProductColorAnalysis(startDate, endDate, seriesName);
            return colorData;
        } catch (Exception e) {
            log.error("获取产品颜色销售分析数据失败", e);
            throw new RuntimeException("获取产品颜色销售分析数据失败", e);
        }
    }

    @Override
    public Object getProductRegionAnalysis(String startDate, String endDate, String level) {
        try {
            List<Map<String, Object>> regionData = omsStatisticsMapper.getProductRegionAnalysis(startDate, endDate, level);
            return regionData;
        } catch (Exception e) {
            log.error("获取客户区域销售分析数据失败", e);
            throw new RuntimeException("获取客户区域销售分析数据失败", e);
        }
    }

    @Override
    public Object getProductTrend(String period, Integer limit, String dimension) {
        try {
            List<Map<String, Object>> trendData = omsStatisticsMapper.getProductTrend(period, limit, dimension);
            return trendData;
        } catch (Exception e) {
            log.error("获取产品销售趋势分析数据失败", e);
            throw new RuntimeException("获取产品销售趋势分析数据失败", e);
        }
    }

    @Override
    public Object getProductDistribution(String startDate, String endDate, String type) {
        try {
            List<Map<String, Object>> distributionData = omsStatisticsMapper.getProductDistribution(startDate, endDate, type);
            
            // 构建图表数据格式
            Map<String, Object> result = new java.util.HashMap<>();
            List<Map<String, Object>> chartData = new ArrayList<>();
            
            BigDecimal totalValue = BigDecimal.ZERO;
            BigDecimal maxValue = BigDecimal.ZERO;
            BigDecimal minValue = new BigDecimal("999999999");
            
            for (Map<String, Object> item : distributionData) {
                Map<String, Object> chartItem = new java.util.HashMap<>();
                chartItem.put("name", item.get("name"));
                chartItem.put("value", item.get("value"));
                chartItem.put("ratio", item.get("ratio"));
                chartItem.put("color", getChartColor(chartData.size()));
                
                chartData.add(chartItem);
                
                BigDecimal value = getBigDecimalValue(item, "value");
                totalValue = totalValue.add(value);
                if (value.compareTo(maxValue) > 0) {
                    maxValue = value;
                }
                if (value.compareTo(minValue) < 0) {
                    minValue = value;
                }
            }
            
            result.put("chartData", chartData);
            
            Map<String, Object> summary = new java.util.HashMap<>();
            summary.put("totalValue", totalValue);
            summary.put("totalCount", distributionData.size());
            summary.put("maxValue", maxValue);
            summary.put("minValue", distributionData.isEmpty() ? BigDecimal.ZERO : minValue);
            result.put("summary", summary);
            
            return result;
        } catch (Exception e) {
            log.error("获取产品销售分布图表数据失败", e);
            throw new RuntimeException("获取产品销售分布图表数据失败", e);
        }
    }

    /**
     * 获取图表颜色
     */
    private String getChartColor(int index) {
        String[] colors = {
            "#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6",
            "#06B6D4", "#84CC16", "#F97316", "#EC4899", "#6366F1"
        };
        return colors[index % colors.length];
    }

    /**
     * 计算增长率
     * @param currentValue 当前值
     * @param lastYearValue 去年同期值
     * @return 增长率（百分比）
     */
    private BigDecimal calculateGrowthRate(BigDecimal currentValue, BigDecimal lastYearValue) {
        if (currentValue == null) {
            currentValue = BigDecimal.ZERO;
        }
        if (lastYearValue == null || lastYearValue.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        
        // 计算增长率: (当前值 - 去年同期值) / 去年同期值 * 100
        BigDecimal difference = currentValue.subtract(lastYearValue);
        BigDecimal growthRate = difference.divide(lastYearValue, 4, BigDecimal.ROUND_HALF_UP)
                                         .multiply(new BigDecimal("100"));
        
        // 保留2位小数
        return growthRate.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    // ==================== 区域销售分析相关方法实现 ====================

    @Override
    public Object getRegionOverview(String startDate, String endDate, String level) {
        try {
            Map<String, Object> result = omsStatisticsMapper.getRegionOverviewStatistics(startDate, endDate, level);
            
            // 获取去年同期数据用于计算增长率
            String lastYearStartDate = null;
            String lastYearEndDate = null;
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                lastYearStartDate = start.minusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                lastYearEndDate = end.minusYears(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
            
            Map<String, Object> lastYearResult = omsStatisticsMapper.getRegionOverviewStatistics(lastYearStartDate, lastYearEndDate, level);
            
            // 计算增长率
            if (result != null && lastYearResult != null) {
                result.put("regionsGrowthRate", calculateGrowthRate(
                    getBigDecimalValue(result, "totalRegions"),
                    getBigDecimalValue(lastYearResult, "totalRegions")
                ));
                result.put("salesGrowthRate", calculateGrowthRate(
                    getBigDecimalValue(result, "totalSales"),
                    getBigDecimalValue(lastYearResult, "totalSales")
                ));
                result.put("avgGrowthRate", calculateGrowthRate(
                    getBigDecimalValue(result, "avgRegionSales"),
                    getBigDecimalValue(lastYearResult, "avgRegionSales")
                ));
                result.put("ratioGrowthRate", calculateGrowthRate(
                    getBigDecimalValue(result, "topRegionRatio"),
                    getBigDecimalValue(lastYearResult, "topRegionRatio")
                ));
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取区域销售概览统计数据失败", e);
            throw new RuntimeException("获取区域销售概览统计数据失败: " + e.getMessage());
        }
    }

    @Override
    public Object getRegionDistribution(String startDate, String endDate, String level, String dataType) {
        try {
            return omsStatisticsMapper.getRegionDistribution(startDate, endDate, level, dataType);
        } catch (Exception e) {
            log.error("获取区域销售分布数据失败", e);
            throw new RuntimeException("获取区域销售分布数据失败: " + e.getMessage());
        }
    }

    @Override
    public Object getRegionRanking(String startDate, String endDate, String level, Integer limit) {
        try {
            return omsStatisticsMapper.getRegionRanking(startDate, endDate, level, limit);
        } catch (Exception e) {
            log.error("获取区域销售排行榜失败", e);
            throw new RuntimeException("获取区域销售排行榜失败: " + e.getMessage());
        }
    }

    @Override
    public Object getRegionGrowth(String period, String level, Integer limit) {
        try {
            return omsStatisticsMapper.getRegionGrowth(period, level, limit);
        } catch (Exception e) {
            log.error("获取区域增长率对比数据失败", e);
            throw new RuntimeException("获取区域增长率对比数据失败: " + e.getMessage());
        }
    }

    @Override
    public Object getRegionTrend(String period, String level, Integer limit) {
        try {
            return omsStatisticsMapper.getRegionTrend(period, level, limit);
        } catch (Exception e) {
            log.error("获取区域销售趋势数据失败", e);
            throw new RuntimeException("获取区域销售趋势数据失败: " + e.getMessage());
        }
    }
}
